const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
const compression = require('compression');

// 导入配置和中间件
const config = require('./config/config');
const { errorHandler, notFound } = require('./middleware/errorHandler');
const logger = require('./util/logger');

// 创建Express应用
const app = express();

// 安全中间件
app.use(helmet());

// 跨域中间件
app.use(cors(config.cors));

// 压缩中间件
app.use(compression());


// 日志中间件
app.use(morgan('combined', {
  stream: {
    write: (message) => logger.info(message.trim())
  }
}));

// 请求体解析中间件
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 请求计时中间件
app.use((req, res, next) => {
  const start = Date.now();
  res.on('finish', () => {
    const duration = Date.now() - start;
    logger.logRequest(req, res, duration);
  });
  next();
});

// 路由
app.use('/', require('./router'));

// 404处理
app.use(notFound);

// 全局错误处理
app.use(errorHandler);

// 优雅关闭
process.on('SIGTERM', () => {
  console.log('SIGTERM received. Shutting down gracefully...');
  process.exit(0);
});

process.on('SIGINT', () => {
  console.log('SIGINT received. Shutting down gracefully...');
  process.exit(0);
});

// 启动服务器
const PORT = config.server.port;
app.listen(PORT, () => {
  console.log(`🚀 Server is running on port ${PORT}`);
  console.log(`🌍 Environment: ${config.server.env}`);
  console.log(`📅 Started at: ${new Date().toISOString()}`);
});

module.exports = app;
